package it.wzm.lightweightlog;

import java.util.LinkedList;
import java.util.Properties;

final class QueueDumper implements Runnable, Constant {

    private long dumpInterval;
    private Queue<? extends Entry> q;
    private Register<? extends Dumper> r;
    private Properties p;

    /**
     * Build a Queue Dumper 
     * @param p Custom set of property
     */
    QueueDumper(Properties p) {
        assert (p != null) : "Property null";
        this.p = p;
        this.init();
    }

    /**
     * Initialize our Queue dumper.
     */
    private void init() {

        // looking for dump interval
        if (p.containsKey("dumpinterval")) {
            this.dumpInterval = (Long) p.get("dumpinterval");
        } else {
            this.dumpInterval = DEFAULT_DUMP_INTERVAL;

        // however by default we cannot dump less then 1 second
        }
        if (this.dumpInterval < 1000) {
            this.dumpInterval = DEFAULT_DUMP_INTERVAL;

        // these are needed by our QueueDumper
        }
        q = ObjectFactory.getQueue();
        r = ObjectFactory.getRegister();

    }

    // implementing the run method
    public void run() {

        // we cannot start a QueueDumper when register does not contain Dumper
        // or the Queue is not cumulable
        if (!q.isCumulable() || r.size() < 1) {
            return;
        }
        try {
            // the current status
            boolean running = true;

            // just an infinite loop
            dumper:
            while (running) {
                // get queue and a list of Entry	
                LinkedList<? extends Entry> l = q.retainAll();

                // basic check if our queue
                // does not contain any Entry...
                if (!l.isEmpty()) {
                    r.dispatchToDumper(l);
                }
                // clear entry from the list...
                l.clear();
                // just pausing a while...
                Thread.sleep(dumpInterval);
            }

        } catch (InterruptedException e) {
            Log.serviceLog(e.getMessage());
        }
    }
}	
	
	

